#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
海康威视相机物体识别系统一键启动器
"""

import os
import sys
import subprocess
import importlib.util

def check_python_version():
    """检查Python版本"""
    if sys.version_info < (3, 7):
        print("错误: 需要Python 3.7或更高版本")
        return False
    print(f"Python版本检查通过: {sys.version}")
    return True

def install_package(package_name, pip_name=None):
    """安装Python包"""
    if pip_name is None:
        pip_name = package_name
    
    try:
        # 检查包是否已安装
        importlib.import_module(package_name)
        print(f"✅ {package_name} 已安装")
        return True
    except ImportError:
        print(f"正在安装 {package_name}...")
        try:
            subprocess.check_call([
                sys.executable, "-m", "pip", "install", 
                pip_name, "-i", "https://pypi.tuna.tsinghua.edu.cn/simple/"
            ])
            print(f"✅ {package_name} 安装成功")
            return True
        except subprocess.CalledProcessError:
            print(f"❌ {package_name} 安装失败")
            return False

def main():
    """主函数"""
    print("=" * 50)
    print("    海康威视相机物体识别系统启动器")
    print("=" * 50)
    print()
    
    # 检查Python版本
    if not check_python_version():
        input("按回车键退出...")
        return
    
    print()
    print("正在检查并安装必要的依赖包...")
    print()
    
    # 需要安装的包
    packages = [
        ("PyQt5", "PyQt5"),
        ("cv2", "opencv-python"),
        ("numpy", "numpy"),
        ("ultralytics", "ultralytics"),
        ("paddleocr", "paddleocr")
    ]
    
    all_installed = True
    for module_name, pip_name in packages:
        if not install_package(module_name, pip_name):
            all_installed = False
    
    if not all_installed:
        print("\n❌ 部分依赖安装失败，程序可能无法正常运行")
        input("按回车键继续...")
    
    print()
    print("依赖检查完成！")
    print()
    
    # 检查BasicDemo目录和主程序文件
    script_dir = os.path.dirname(os.path.abspath(__file__))
    basic_demo_dir = os.path.join(script_dir, "BasicDemo")
    main_script = os.path.join(basic_demo_dir, "object_recognition_demo.py")
    
    if not os.path.exists(basic_demo_dir):
        print("❌ 错误: 未找到BasicDemo目录")
        input("按回车键退出...")
        return
    
    if not os.path.exists(main_script):
        print("❌ 错误: 未找到object_recognition_demo.py文件")
        input("按回车键退出...")
        return
    
    print("正在启动物体识别系统...")
    print("请确保相机已连接并正常工作")
    print()
    
    try:
        # 切换到BasicDemo目录
        os.chdir(basic_demo_dir)
        
        # 运行主程序
        subprocess.run([sys.executable, "object_recognition_demo.py"])
        
    except KeyboardInterrupt:
        print("\n程序被用户中断")
    except Exception as e:
        print(f"\n程序运行出错: {e}")
    
    print()
    print("程序已退出")
    input("按回车键退出...")

if __name__ == "__main__":
    main() 